<template>
  <input type="file" @change="onChange" />
</template>

<script lang="ts" setup>
import { getFileChunkListAndHash } from '@/utils'
import axios from 'axios'
axios.defaults.baseURL = 'http://127.0.0.1:3000'

function onChange(event: Event) {
  const file = (event.target as HTMLInputElement).files?.[0] as File

  console.time('hello')
  getFileChunkListAndHash(file).then(async (value) => {
    console.log('value.chunkList', value.chunkList)
    console.log('value.hash', value.hash)

    // 初始化接口
    const response1 = await axios.post('/api/uploadInit', {
      name: file.name // 文件名
    })
    // 获取到 uploadId
    const uploadId = response1.data.data

    // 一个一个切片的上传
    const promiseList = []
    for (let i = 0; i < value.chunkList.length; i++) {
      // 追加到 promiseList 中
      promiseList.push(
        axios.post(
          '/api/uploadPart',
          {
            partIndex: i, // 切片下标
            partFile: value.chunkList[i], // 切片内容
            uploadId // 上传Id
          },
          {
            headers: {
              // 文件上传，一定要注意修改 Content-Type
              'Content-Type': 'multipart/form-data'
            }
          }
        )
      )
    }

    await Promise.all(promiseList)

    // 通知后端合并
    const response = await axios.post('/api/uploadComplete', {
      uploadId, // 上传Id
      name: file.name, // 文件名
      md5: value.hash // 文件hash
    })
    console.log('response.data', response.data)
    console.timeEnd('hello')
  })
}
</script>
